"""
---------------------------------------------------------------------
- File: service.py
- Date: 2025/8/8
- Author: yangzhide
- Email: xxzjyzd@126.com
- Description:
---------------------------------------------------------------------
"""

from datetime import datetime, timedelta, timezone

import jwt
from fastapi import HTTPException
from passlib.context import CryptContext

# models
from app.models.system_manage.user import User

# token相关配置
from app.core.config import SECRET_KEY, ALGORITHM

pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")


def get_password_hash(password):
    """密码哈希"""
    return pwd_context.hash(password)


def verify_password(plain_password, hashed_password):
    """验证密码"""
    return pwd_context.verify(plain_password, hashed_password)


async def authenticate_user(user_no, password):
    user = await User.get_or_none(user_no=user_no)
    if not user:
        raise HTTPException(
            status_code=401,
            detail="登录账号不存在",
            headers={"WWW-Authenticate": "Bearer"},
        )
    else:
        if not verify_password(password, user.password):
            raise HTTPException(
                status_code=401,
                detail="登录密码不正确",
                headers={"WWW-Authenticate": "Bearer"},
            )
        if not user.status:
            raise HTTPException(
                status_code=403,
                detail="账号不可用",
                headers={"WWW-Authenticate": "Bearer"},
            )
    return user


async def create_access_token(data: dict, expires_delta: timedelta | None = None):
    """生成token"""
    to_encode = data.copy()
    if expires_delta:
        expire = datetime.now(timezone.utc) + expires_delta
    else:
        expire = datetime.now(timezone.utc) + timedelta(minutes=15)

    to_encode.update({"exp": expire})
    encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
    return encoded_jwt
